package com.dcy.daily.skill.jvm.memoryAlloc.toolsOfJvm;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Java监视与管理控制台，对应Jvm书P157,是可视化监视、管理工具。
 * 包括概述、内存监控、线程监控。该示例展示了线程监控。在JDK/bin运行JConsole.exe
 *
 * @author duanchunyu
 * @version 1.0.0
 * @createTime 2021年06月02日 21:15:00
 */
public class JConsole_ThreadMonitorUsage {

    /**
     * 线程死循环
     */
    public static void createBusyThread(){
        Thread thread = new Thread(()-> {
            while (true) ;
        },"testBusyThread");
        thread.start();
    }

    /**
     * 线程锁等待演示
     * @param lock
     */
    public static void createLockThread(final Object lock){
        Thread thread = new Thread(() -> {
            synchronized (lock){
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"testLockThread");
        thread.start();
    }

    public static void Usage1() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        br.readLine();
        createBusyThread();
        br.readLine();
        Object obj = new Object();
        createLockThread(obj);
    }

    /**
     * 线程死锁演示
     */
    static class SynAddRunable implements Runnable{
        int a,b;
        public SynAddRunable(int a,int b){
            this.a = a;
            this.b = b;
        }

        @Override
        public void run() {
            synchronized (Integer.valueOf(a)){
                synchronized (Integer.valueOf(b)){
                    System.out.println(a + b);
                }
            }
        }
    }

    public static void Usage2() throws IOException {
        for (int i = 0; i < 100; i++) {
            new Thread(new SynAddRunable(1,2)).start();
            new Thread(new SynAddRunable(2,1)).start();
        }
    }

    public static void main(String[] args) throws IOException {
//        Usage1();
        Usage2();
    }
}
